function hwk3(whichCase, K1)
% Usage:
%  hwk3(whichCase)
%
% Arguments
% whichCase - 1,2, or 3
% K1 - Constant (try 0.1)
%
% Paul Ozog
% Communication Systems

A = 1;
fc = 10e3;
fs = 4*fc;
f0 = fc / 100;
phi0 = pi/3;
T = 1000/fc;
Ts = 1/fs;
t = 0:Ts:T;
M = (2*fs)/fc;
N = T/Ts;
n = 0:N;
K2 = K1/10;
phim = 3;
fm = fc / 1000;

switch whichCase
 case 1,
  phi = phi0 * ones(1,N+1);
 case 2,
  phi = 2*pi*f0*t;
 case 3,
  phi = phim * cos(2*pi*fm*t);
end

r = A * cos( 2*pi*fc*t + phi);

x = zeros(1,7);
e = [];
phiH = [0];

for currentn=n(1):n(end)
  currentn = currentn+1; %normalize 0 to 1 etc...
  nextn = currentn + 1;
  x(currentn+M-1) = -2 * sin(2*pi*fc*(currentn-1)*Ts + phiH(currentn)) * r(currentn);
  e(currentn) = (1/M) * sum(x(currentn:currentn+M-1));
  phiH(nextn) = phiH(currentn) + K1*e(currentn) + K2*sum(e);
end

if (K1 > .4),
  linewidth=1;
else,
  linewidth=3;
end

plot(t, phiH(1:end-1), '--r', 'LineWidth',linewidth)
hold on
plot(t, phi(1:end))
title(['\phi when K1 = ', num2str(K1)])
xlabel('Time (seconds)')
legend('Estimated \phi(t)', 'Actual \phi(t)')
